package weaver.interfaces.dsjj.duss.docCronJob;

import weaver.conn.RecordSet;
import weaver.conn.RecordSetDataSource;
import weaver.docs.webservices.DocAttachment;
import weaver.docs.webservices.DocInfo;
import weaver.docs.webservices.DocServiceImpl;
import weaver.general.BaseBean;
import weaver.general.StaticObj;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.interfaces.datasource.DataSource;
import weaver.interfaces.dsjj.duss.TransMethod;
import weaver.interfaces.schedule.BaseCronJob;

import java.io.BufferedReader;
import java.io.File;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;

/**
 * @Title: ecology-9-demo
 * @Company: 泛微软件
 * @author: weaver.Dusongsong
 * @version: 1.0
 * @CreateDate: 2020-06-06
 * @Description: 定时任务同步亚微公文
 * @ModifyLog:
 **/

public class CreateWorkflowCron extends BaseCronJob {
    @Override
    public void execute() {
        BaseBean baseBean = new BaseBean();
        String time = TransMethod.getTime();
        String timebefore = TransMethod.getTimebefore();
        baseBean.writeLog( "CreateFgdzcWorkflow---timebefore=" + timebefore + ",curtime=" + time );
        DataSource ds = (DataSource) StaticObj.getServiceByFullname( ("datasource.YaWei"), DataSource.class );
        Connection conn = ds.getConnection();
        RecordSet rs2 = new RecordSet();
        RecordSet rs3 = new RecordSet();
        RecordSetDataSource rs = new RecordSetDataSource( "YaWei" );//外部数据源标识
        WorkflowCreateHandler handler = new WorkflowCreateHandler();
        String SQL = "select t.GUID,p.ReceivePersonGuid,t.createTime,t.title,t.fileCode,t.sendPersonGuid " +
                " from NotePaper t left join NotePaperPerson p on t.GUID=p.GUID " +
                " where t.fileSort='公文' and t.status='2' and t.createTime >= '" + timebefore + "' and t.createTime <'" + time + "'";
        rs.execute( SQL );
        while (rs.next()) {
            String GUID = Util.null2String( rs.getString( "GUID" ) );
            String createday = Util.null2String( rs.getString( "createTime" ) );
            String title = Util.null2String( rs.getString( "title" ) );
            String fileCode = Util.null2String( rs.getString( "fileCode" ) );
            String sendPersonGuid = Util.null2String( rs.getString( "sendPersonGuid" ) );
            String ReceivePersonGuids = Util.null2String( rs.getString( "ReceivePersonGuid" ) );

            if (!"".equals( sendPersonGuid ) || !"".equals( ReceivePersonGuids )) {
                String[] arr = ReceivePersonGuids.split( ";" );
                String swys = "";
                for(int i=0;i<arr.length;i++){
                    String resourceid = TransMethod.HRtransGUIDtoID(arr[i]);
                    if(!"".equals(resourceid)){
                        swys += swys == "" ?  resourceid : "," + resourceid ;
                    }
                }
                for (String ReceivePersonGuid : arr) {
                    try {
                        String sql1 = "select a.title,a.fileExt,i.content " +
                                "from Attachmentinfo a left join BLOBInfo i on a.GUID=i.GUID and a.BLOBGUID=i.BLOBGUID where a.GUID=?";
                        PreparedStatement pstm = conn.prepareStatement( sql1 );
                        pstm.setString( 1, GUID );
                        ResultSet rs1 = pstm.executeQuery();
                        String docids = "";
                        int docid = -1;
                        while (rs1.next()) {
                            String filename = Util.null2String( rs1.getString( "title" ) );
                            String filetype = Util.null2String( rs1.getString( "fileExt" ) );
                            String userid = TransMethod.HRtransGUIDtoID( sendPersonGuid );
                            Clob clob = rs1.getClob( "content" );
                            String readline = "";
                            StringBuffer sb = new StringBuffer();
                            BufferedReader br = new BufferedReader( clob.getCharacterStream() );
                            while ((readline = br.readLine()) != null) {
                                sb = sb.append( readline );
                            }
                            br.close();
                            String doccontent = sb.toString();
                            DocServiceImpl docserviceimpl = new DocServiceImpl();
                            DocAttachment[] docattachment = new DocAttachment[1];
                            DocAttachment da = new DocAttachment();
                            da.setFilename( filename );//附件标题
                            da.setFilecontent( doccontent ); //附件内容
                            da.setFiletype( filetype ); //imagefiletype
                            da.setIszip( 0 );//是否压缩
                            da.setIsAesEncrype( 1 );//是否加密
                            da.setAesCode( "0" );
                            da.setIsextfile( "1" ); //附件是否是office类型
                            if (filetype.equalsIgnoreCase( "doc" )) {
                                da.setDocfiletype( "3" );
                            } else if (filetype.equalsIgnoreCase( "xls" )) {
                                da.setDocfiletype( "4" );
                            } else if (filetype.equalsIgnoreCase( "ppt" )) {
                                da.setDocfiletype( "5" );
                            } else if (filetype.equalsIgnoreCase( "wps" )) {
                                da.setDocfiletype( "6" );
                            } else if (filetype.equalsIgnoreCase( "docx" )) {
                                da.setDocfiletype( "7" );
                            } else if (filetype.equalsIgnoreCase( "xlsx" )) {
                                da.setDocfiletype( "8" );
                            } else if (filetype.equalsIgnoreCase( "pptx" )) {
                                da.setDocfiletype( "9" );
                            } else {
                                da.setDocfiletype( "2" );
                            }
                            da.setImagefilename( filename + "." + filetype );// 附件标题
                            docattachment[0] = da;
                            DocInfo doc = new DocInfo(); //创建文档
                            doc.setMaincategory( 0 );//主目录id
                            doc.setSubcategory( 0 );//分目录id
                            doc.setSeccategory( 159 );//子目录id
                            doc.setDocSubject( filename );//标题
                            doc.setDoccontent( "" );//文档内容
                            doc.setAttachments( docattachment );
                            baseBean.writeLog( "userid=" + userid );
                            if (!"".equals( userid )) {
                                User user = new User( Util.getIntValue( userid ) );
                                docid = docserviceimpl.createDocByUser( doc, user );
                                baseBean.writeLog( "docid=" + docid );
                                if (docid != -1) {
                                    rs2.executeQuery( "select filerealpath from imagefile where imagefileid in (select imagefileid from docimagefile where docid in ('" + docid + "'));" );
                                    rs2.next();
                                    String filepath = Util.null2String( rs2.getString( "filerealpath" ) );
                                    File file = new File( filepath );
                                    baseBean.writeLog( "filename:" + file.getName() );
                                    String srcfilepath = filepath.substring( 0, filepath.indexOf( '.' ) ) + ".doc";
                                    TransMethod.hexToFile( doccontent, srcfilepath );
                                    if (file.getName().endsWith( ".zip" )) {  // zip文件  判断 是否存在
                                        if (file.delete()) {
                                            String newfilepath = filepath.substring( 0, filepath.indexOf( '.' ) ) + ".zip";
                                            TransMethod.doZip( srcfilepath, newfilepath, 2 );
                                        }
                                    }
                                    docids += docids == "" ? docid + "" : "," + docid;
                                }
                            }
                        }
                        String swy = TransMethod.HRtransGUIDtoID( ReceivePersonGuid );
                        String swy1 = swys;
                        String swdw = TransMethod.bmIdTransMethod( ReceivePersonGuid );
                        String lwdw = TransMethod.bmIdTransMethod( sendPersonGuid );
                        String fjr = TransMethod.HRtransGUIDtoID( sendPersonGuid );
                        String swsj = createday.substring( 0, 10 );
                        String workflowId = "163";
                        String IsNextFlow = "1";
                        String createdate = createday.substring( 0, 10 );//2020-08-09 15:20:15
                        String createtime = createday.substring( 11, 19 );
                        Map<String, String> requestMainMap = new HashMap<>();
                        if(!"".equals( swy )){
                            requestMainMap.put( "swy", swy );
                        }
                        if(!"".equals( swdw )){
                            requestMainMap.put( "swdw", swdw );
                        }
                        if(!"".equals( lwdw )){
                            requestMainMap.put( "lwdw", lwdw );
                        }
                        if(!"".equals( fjr )){
                            requestMainMap.put( "fjr", fjr );
                        }
                        requestMainMap.put( "swy1", swy1 );
                        requestMainMap.put( "swsj", swsj );
                        requestMainMap.put( "wjbt", title );
                        requestMainMap.put( "lwzh", fileCode );
                        requestMainMap.put( "xgfj", docids );
                        baseBean.writeLog( "requestMainMap=" + requestMainMap.toString() );
                        String creatorId = swy;
                        String requestName = title;
                        String reqeustid = handler.WorkflowCreateByRequestMap( creatorId, workflowId, requestName, IsNextFlow, requestMainMap );
                        if (Util.getIntValue( reqeustid ) > 0) {
                            rs3.executeUpdate( "update workflow_requestbase set createdate='" + createdate + "', createtime='" + createtime + "' where requestid = '" + reqeustid + "'" );
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        baseBean.writeLog( "e:" + e );
                    }
                }
            }else {
             baseBean.writeLog("唯一标识为["+GUID+"]的收件人或者发件人为空,时间为"+timebefore+"-"+time+"");
            }
        }
    }
}
